var rABS = false; //是否将文件读取为二进制字符串
var shopData = []; //商户数据
var agentData = [];//代理商数据
var shopCity = [];//商户城市
var shopOption = '';
var agentOption = '';
var excel;
var agentCity;
var shopSelect = document.querySelector('#shop_select');//商户
var agentSelect = document.querySelector('#agent_select');//代理商
var shopExcel = document.querySelector('#shop_excel');//邮件内容
var addressee = document.querySelector('#addressee');//收件人
var mailLog = document.querySelector('#mail_log');//邮件日志
var alert=document.querySelector('.am-modal-bd');
var city = [];
// 导入
function importf(obj) {
    if (!obj.files) { return; }
    var f = obj.files[0];
    {
        var reader = new FileReader();
        var name = f.name;
        reader.onload = function (e) {
            var data = e.target.result;
            var wb;
            if (rABS) {
                wb = XLSX.read(data, { type: 'binary' });
            } else {
                var arr = fixdata(data);
                wb = XLSX.read(btoa(arr), { type: 'base64' });
            }
            // 商户
            if (obj.id == 'shop') {
                shopData = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
                if (shopData.length != 0) {
                    // console.log('商户导入成功');
                    document.querySelector('.shop').style.backgroundImage="url('img/green.png')";
                    console.log(document.querySelector('.shop').style.backgroundImage)
                }
                shopData.forEach(function (item, index) {
                    if (shopCity.indexOf(item.城市) < 0) {
                        shopOption += `<option>${item.城市}</option>`;
                        shopCity.push(item.城市);
                    }
                })
                shopSelect.innerHTML = shopOption;
                textAreaContent(shopSelect.value);
            }
            // 代理商
            else if (obj.id == 'agent') {
                agentData = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
                if (agentData.length != 0) {
                    // console.log('代理商导入成功');
                    document.querySelector('.agent').style.backgroundImage="url('img/green.png')";
                }
                if (shopSelect.value) {
                    textAreaContent(shopSelect.value);
                }
            }
        };
        if (rABS) reader.readAsBinaryString(f);
        else reader.readAsArrayBuffer(f);
    }
}

function fixdata(data) {
    var o = "", l = 0, w = 10240;
    for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
    return o;
}

function changeData(obj) {
    textAreaContent(obj.value);
}

function changeAgentData(obj) {
    addressee.innerHTML = agentCity.filter(item => item.合伙人名称 == obj.value)[0].邮箱地址
}

// 邮件内容
function textAreaContent(value) {
    excel = shopData.filter(item => item.城市 == value);
    shopExcel.innerHTML = '';
    excel.forEach(function (item) {
        shopExcel.innerHTML += `${item.店铺名称}&nbsp &nbsp &nbsp${item.城市}&nbsp &nbsp &nbsp${item.电话}&nbsp &nbsp &nbsp${item.地址}\n`;
    })
    agentSelect.innerHTML = ' ';
    if (agentData.length != 0) {
        agentCity = agentData.filter(item => item.城市 == value);
        console.dir(agentCity);
        // 从大到小
        agentCity.sort(function (a, b) {
            return a.有效账号数 - b.有效账号数 < 0;
        })
        console.dir(agentCity)
        if (agentCity.length != 0) {
            agentCity = agentCity.filter(item => item.有效账号数 == agentCity[0].有效账号数)
            console.dir(agentCity)
            agentCity.forEach(function (item) {
                agentSelect.innerHTML += `<option>${item.合伙人名称}</option>`;
            })
            addressee.innerHTML = agentCity.filter(item => item.合伙人名称 == agentSelect.value)[0].邮箱地址
        }
        else if (agentCity.length == 0) {
            agentSelect.innerHTML = ' ';
        }
    }
}

// 导出
function saveAs(obj, fileName) {
    //当然可以自定义简单的下载文件实现方式 
    var tmpa = document.createElement("a");
    tmpa.download = fileName || "下载";
    tmpa.href = URL.createObjectURL(obj); //绑定a标签
    tmpa.click(); //模拟点击实现下载
    alert.innerHTML='导入成功';
    setTimeout(function () { //延时释放
        URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
    }, 100);
}

const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };//这里的数据是用来定义导出的格式类型

function downloadExl(data, type) {
    if (data == '') {
        alert.innerHTML='导入失败';
        return
    }
    const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
    wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data);//通过json_to_sheet转成单页(Sheet)数据
    saveAs(new Blob([s2ab(XLSX.write(wb, wopts))], { type: "application/octet-stream" }), "商户" + '.' + (wopts.bookType == "biff2" ? "xls" : wopts.bookType));
}
function s2ab(s) {
    if (typeof ArrayBuffer !== 'undefined') {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    } else {
        var buf = new Array(s.length);
        for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
}
//发送邮件
function sendMail() {
    if (addressee.innerHTML == '' && shopExcel.value.trim() == '') {
        alert.innerHTML='发送失败';
        return
    }
    $.ajax({
        url: "",
        type: 'post',
        data: {
            person: addressee.innerHTML,
            content: shopExcel.innerHTML
        },
        success: function (data) {
            alert.innerHTML='发送成功';
            mailLog.innerHTML += agentSelect.value + '&nbsp &nbsp &nbsp' + '发送成功\n'
            if (city.indexOf(shopSelect.value) < 0) {
                city.push(shopSelect.value);
                // 修改shopData数据
                shopData.forEach(function (item) {
                    if (item.城市 == shopSelect.value) {
                        item.代理商 = agentSelect.value;
                    }
                })
            }
        },
        error: function () {
            alert.innerHTML='发送失败';
            // mailLog.innerHTML+=agentSelect.value+'&nbsp &nbsp &nbsp'+'发送失败\n';
                mailLog.innerHTML += `<span class='log_left'>${agentSelect.value}</span><span class='log_right'>发送成功</span></br>` 
            if (city.indexOf(shopSelect.value) < 0) {
                city.push(shopSelect.value);
                // 修改shopData数据
                shopData.forEach(function (item) {
                    if (item.城市 == shopSelect.value) {
                        item.代理商 = agentSelect.value;
                    }
                })
            }
        }
    });
}